package com.linefly.online_car;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.utils.SpatialRelationUtil;
import com.amap.api.maps.utils.overlay.SmoothMoveMarker;
import com.linefly.online_car.Custom.MyLoading;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import Been.been_fuifang_event;
import Socket.PlayBackClient;
import Util.DateUtil;
import Util.NavigationBarUtil;
import Util.PreferenceUtil;
import cn.pedant.SweetAlert.SweetAlertDialog;

import static com.autonavi.amap.mapcore.maploader.NetworkState.isNetworkConnected;

public class HuiFang extends AppCompatActivity {
    MapView mMapView = null;
    AMap aMap;
    private UiSettings mUiSettings;//定义一个UiSettings对象
    private URI uri;
    private String token = "";
    private boolean isduanwangFlag = false;
    private boolean isyouwang = false;
    private PlayBackClient exampleClient, duanwangClient;
    String st,ed,id;
    List<HashMap> points = new ArrayList<HashMap>();
    private Polyline mPolyline;

    List<LatLng> arrayList = new ArrayList<>();//存放点经纬度
    SmoothMoveMarker smoothMarker;
    private SeekBar seekBar;
    //计时器
    private Handler mhandle = new Handler();
    private boolean isPause = false;//是否暂停
    private Runnable timeRunable;

    private long totalTime;//总时长
    private long currentTime;//当前时长
    private long startTime;//开始时长
    private long finalTime;//最后的时间

    TextView tv_time1,tv_time2,tv_speed;
    ImageView imageView_bofang;
    int flag_bo = 1;
    int speed = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hui_fang);




        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        }


        if (NavigationBarUtil.hasNavigationBar(this)) {
            NavigationBarUtil.initActivity(findViewById(android.R.id.content));//解决底部适配
        }
        Intent intent = getIntent();
        st = intent.getStringExtra("st");
        ed = intent.getStringExtra("ed");
        id= intent.getStringExtra("id");
        token = PreferenceUtil.getString("token", "");
        Log.e("token", "ws://f.super-gps.net/wstrack/"+token+"/"+st+"/"+ed);
        uri = URI.create("ws://f.super-gps.net/wstrack/"+token+"/"+st+"/"+ed);
        tv_time1 = (TextView)findViewById(R.id.time1);
        tv_time2 = (TextView)findViewById(R.id.time2);
        tv_speed = (TextView)findViewById(R.id.tv_speed);
        imageView_bofang = (ImageView)findViewById(R.id.bofang);
        seekBar = (SeekBar) findViewById(R.id.seekBar2);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 当拖动条的滑块位置发生改变时触发该方法,在这里直接使用参数progress，即当前滑块代表的进度值
                currentTime = startTime + seekBar.getProgress() *totalTime/100;
                tv_time1.setText(DateUtil.getDateToString(currentTime,"HH:mm:ss"));

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Log.e("------------", "开始滑动！");
                isPause = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

                currentTime = startTime + seekBar.getProgress() *totalTime/100;
                move();
                isPause = false;
                tv_time1.setText(DateUtil.getDateToString(currentTime,"HH:mm:ss"));
                smoothMarker.setTotalDuration((int) (finalTime - startTime)/speed);
                Log.e("------------", "停止滑动！"+String.valueOf(currentTime));
            }
        });



        EventBus.getDefault().register(HuiFang.this);

        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);


        if (aMap == null) {
            aMap = mMapView.getMap();


        }
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        // 自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(0);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.gps_point));
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationEnabled(false);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setCompassEnabled(false);
        mUiSettings.setScaleControlsEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setTiltGesturesEnabled(false);



        MyLoading.show(HuiFang.this);




    }

    public void click_bofang(View v){
        if(smoothMarker!=null){
            if(flag_bo == 1){
                imageView_bofang.setBackgroundResource(R.mipmap.zanting);
                flag_bo = 0;
                isPause = true;
                smoothMarker.stopMove();
            }else {
                imageView_bofang.setBackgroundResource(R.mipmap.bofang);
                flag_bo = 1;
                isPause = false;
                smoothMarker.startSmoothMove();
            }
        }
    }

    public void click_jin(View v){
        if(speed<32){
            speed*=2;
        }
        tv_speed.setText(String.valueOf(speed)+"倍");
        smoothMarker.setTotalDuration((int) (finalTime - startTime)/speed);
    }
    public void click_tui(View v){
        if(speed>1){
            speed/=2;
        }
        tv_speed.setText(String.valueOf(speed)+"倍");
        smoothMarker.setTotalDuration((int) (finalTime - startTime)/speed);
    }
    public void sock1() {
        /*
        方法三
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!isduanwangFlag) {
                    exampleClient = new PlayBackClient(uri);
                    exampleClient.setConnectionLostTimeout(0);
                    exampleClient.startSoc(exampleClient,id);
                } else {
                    exampleClient.reconnect(); //这里有点问题,断网后的重连
                }

            }
        }).start();

    }





    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(been_fuifang_event carsbeen) {
        Log.e("回放", String.valueOf(carsbeen.getType())+"  "+String.valueOf(carsbeen.getWeidu()
                +"  "+String.valueOf(carsbeen.getJingdu()))+"  "+String
                .valueOf((long)carsbeen.getDianya())+"  ");



        if(carsbeen.getJingdu() == 111.0 && carsbeen.getWeidu() == 111.0){
            MyLoading.cancel();
            if(points.size()>0) {
                long time1 = (long)(double)points.get(0).get("time");//开始时间
                long time2 =  (long)(double)points.get(points.size() - 1).get("time");//结束时间
                currentTime = time1;
                startTime = time1;
                finalTime = time2;
                totalTime = time2 - time1;
                tv_time1.setText(DateUtil.getDateToString(time1,"HH:mm:ss"));
                tv_time2.setText(DateUtil.getDateToString(time2,"HH:mm:ss"));
                Log.e("计数器", String.valueOf(currentTime) +"     "+String.valueOf(finalTime));
                timeRunable = new Runnable() {
                    @Override
                    public void run() {

                        if (!isPause) {

                            seekBar.setProgress((int)((currentTime - startTime)*100/totalTime));
                            tv_time1.setText(DateUtil.getDateToString(currentTime,"HH:mm:ss"));
                            currentTime+=speed;
                            if(currentTime>=finalTime){
                                isPause = true;
                                smoothMarker.stopMove();

                            }
                            Log.e("计数器", String.valueOf(currentTime)+"差值"+String.valueOf((int)((currentTime - startTime)*100/totalTime)));
                            //递归调用本runable对象，实现每隔一秒一次执行任务


                        }
                        mhandle.postDelayed(this, 1000);
                    }
                };
                mhandle.post(timeRunable);


                addPolylineInPlayGround();                                                                                                      addPolylineInPlayGround();
                move();
            }else {
                new SweetAlertDialog(HuiFang.this)
                        .setTitleText("暂无数据")
                        .setConfirmText("确定")
                        .setCancelText("取消")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                sDialog.dismissWithAnimation();
                                finish();

                            }
                        })
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismissWithAnimation();
                                finish();
                            }
                        })
                        .show();
            }
        }else {

            HashMap hashMap1 = new HashMap();
            hashMap1.put("lat",carsbeen.getWeidu());
            hashMap1.put("lng",carsbeen.getJingdu());
            hashMap1.put("time",carsbeen.getDianya());
            points.add(hashMap1);
        }



    }
    /**
     * 添加轨迹线
     */
    private void addPolylineInPlayGround() {

//        List<Integer> colorList = new ArrayList<Integer>();
//        List<BitmapDescriptor> bitmapDescriptors = new ArrayList<BitmapDescriptor>();
//
//        int[] colors = new int[]{Color.argb(255, 0, 255, 0),Color.argb(255, 255, 255, 0),Color.argb(255, 255, 0, 0)};
//
//        //用一个数组来存放纹理
//        List<BitmapDescriptor> textureList = new ArrayList<BitmapDescriptor>();
//        //textureList.add(BitmapDescriptorFactory.fromResource(R.mipmap.custtexture));
//
//        List<Integer> texIndexList = new ArrayList<Integer>();
//        texIndexList.add(0);//对应上面的第0个纹理
//        texIndexList.add(1);
//        texIndexList.add(2);
//
//        Random random = new Random();
//

        for (int i = 0; i < points.size(); i++) {
           // colorList.add(colors[random.nextInt(3)]);
           // bitmapDescriptors.add(textureList.get(0));
            HashMap hashMap1 =  (HashMap)points.get(i);
            LatLng latLng =new LatLng((double)hashMap1.get("lat"),(double)hashMap1.  get("lng"));
            arrayList.add(latLng);

        }
//
//        mPolyline = aMap.addPolyline(new PolylineOptions().setCustomTexture(BitmapDescriptorFactory.fromResource(R.mipmap.custtexture)) //setCustomTextureList(bitmapDescriptors)
//				.setCustomTextureIndex(texIndexList)
//                .addAll(arrayList)
//                .useGradient(true)
//                .width(18));
//
//        LatLngBounds.Builder builder = new LatLngBounds.Builder();
//        builder.include(arrayList.get(0));
//        builder.include(arrayList.get(points.size() - 2));
//
//        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));


        Polyline polyline =aMap.addPolyline(new com.amap.api.maps.model.PolylineOptions().
                addAll(arrayList).width(10).color(Color.argb(255, 1, 1, 1)));
    }

    public void move(){
        // 获取轨迹坐标点
        arrayList.clear();//清除全部的经纬度点
        for (int i = 0; i < points.size(); i++) {//添加超过了当前时长的点
            HashMap hashMap1 = points.get(i);
            if ((long) (double) hashMap1.get("time") >= currentTime) {
                LatLng latLng = new LatLng((double) hashMap1.get("lat"), (double) hashMap1.get("lng"));
                arrayList.add(latLng);
            }
        }

        if(smoothMarker!=null) {
            smoothMarker.stopMove();
        }


            //LatLngBounds bounds = new LatLngBounds(arrayList.get(0), arrayList.get(arrayList.size() - 2));
            //aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));

            if (smoothMarker == null) {
                smoothMarker = new SmoothMoveMarker(aMap);

            }
// 设置滑动的图标

            smoothMarker.setDescriptor(BitmapDescriptorFactory.fromResource(R.mipmap.icon_car));
            LatLng drivePoint = arrayList.get(0);
            Pair<Integer, LatLng> pair = SpatialRelationUtil.calShortestDistancePoint(arrayList, drivePoint);
            arrayList.set(pair.first, drivePoint);
            List<LatLng> subList = arrayList.subList(pair.first, arrayList.size());

// 设置滑动的轨迹左边点
            smoothMarker.setPoints(subList);
// 设置滑动的总时间
            smoothMarker.setTotalDuration((int) (finalTime - currentTime));
// 开始滑动

        if(flag_bo == 0) {
            imageView_bofang.setBackgroundResource(R.mipmap.bofang);
            flag_bo = 1;
            isPause = false;
        }

        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(arrayList.get(0).latitude, arrayList.get(0).longitude)));
            smoothMarker.startSmoothMove();




    }

    public boolean isWifiConnected(Context context) {//判读wifi是否可用
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isAvailable();
            }
        }
        return false;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        mMapView.onDestroy();


    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        isyouwang = isNetworkConnected(HuiFang.this) || isWifiConnected(HuiFang.this);
        if (isyouwang && !isduanwangFlag) {
            sock1();

        } else if (isyouwang && isduanwangFlag) {
            if (exampleClient != null) {
                exampleClient.close();
                exampleClient = null;
            }
            if (exampleClient == null) {
                sock1();

            }
        } else if (!isyouwang) {
            isduanwangFlag = true;
        }

        mMapView.onResume();
    }

    public void click_back(View v){
        finish();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
        mhandle.removeCallbacks(timeRunable);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

}
